package com.dunqi.gpm.shunqing.home.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatSpinner;
import android.text.TextUtils;
import android.transition.Visibility;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.dunqi.gpm.shunqing.R;
import com.dunqi.gpm.shunqing.common.api.ApiFactory;
import com.dunqi.gpm.shunqing.common.api.RxSchedulers;
import com.dunqi.gpm.shunqing.common.base.ComObserver;
import com.dunqi.gpm.shunqing.common.base.Data;
import com.dunqi.gpm.shunqing.common.base.UploadFileActivity;
import com.dunqi.gpm.shunqing.common.util.FormUtil;
import com.dunqi.gpm.shunqing.common.util.JsonUtils;
import com.dunqi.gpm.shunqing.common.util.RequestBodyUtil;
import com.dunqi.gpm.shunqing.common.util.TimeUtil;
import com.dunqi.gpm.shunqing.common.view.ComTitleBar;
import com.dunqi.gpm.shunqing.common.view.NoScrollGridView;
import com.dunqi.gpm.shunqing.home.adapter.SpinnerAdapter;
import com.dunqi.gpm.shunqing.home.bean.BelongType;
import com.dunqi.gpm.shunqing.home.bean.Project;
import com.dunqi.gpm.shunqing.home.bean.ProjectWorkTrend;
import com.dunqi.gpm.shunqing.home.widget.DatePickerDiaglog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;

public class CreateProjectTrendActivity extends UploadFileActivity {


    private static final String CATEGORYCODE = "categorycode";
    private static final String DATA = "data";
    private static String PROWORKTRENDID = "proWorkTrendId";
    @BindView(R.id.title_bar)
    ComTitleBar titleBar;
    @BindView(R.id.spinner_project)
    AppCompatSpinner spinnerProject;
    @BindView(R.id.spinner_type)
    AppCompatSpinner spinnerType;
    @BindView(R.id.title_edit)
    EditText titleEdit;
    @BindView(R.id.time_tv)
    TextView timeTv;
    @BindView(R.id.remark_edit)
    EditText remarkEdit;
    @BindView(R.id.grid_view)
    NoScrollGridView gridView;
    @BindView(R.id.trend_content_edit)
    EditText trendContentEdit;
    private String time;
    ArrayList<Project> projects = new ArrayList<>();
    ArrayList<BelongType> types = new ArrayList<>();
    private Long proWorkTrendId;
    private String categoryCode;
    private HashMap<String, String> reciveData;

    @Override
    protected void refreshData(Bundle savedInstanceState) {

//        getProjectWorkTrendInfo

        /*
        if (proWorkTrendId == null) {
            netProjectList();
        } else {
            getProjectWorkTrendInfo();
        }
        */


        netTypes();
    }

    private void getProjectWorkTrendHtmlContentInfo() {
        ApiFactory.getInstance()
                .getProjectWorkTrendInfo(proWorkTrendId)
                .compose(RxSchedulers.<Data<ProjectWorkTrend>>io_main())
                .subscribe(new ComObserver<ProjectWorkTrend>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposables(d);
                    }

                    @Override
                    public void onSuccess(ProjectWorkTrend projectWorkTrend) {
                        if (projectWorkTrend == null) {
                            return;
                        }
                        trendContentEdit.setText(projectWorkTrend.getTrendHtmlContent());
                    }

                    @Override
                    public void onFinal() {

                    }
                });
    }

    private void netTypes() {
        ApiFactory.getInstance()
                .getListByGroup("project_work_trend_type")
                .compose(RxSchedulers.<Data<ArrayList<BelongType>>>io_main())
                .subscribe(new ComObserver<ArrayList<BelongType>>() {
                    @Override
                    public void onSuccess(ArrayList<BelongType> belongTypePage) {
                        if (belongTypePage == null) {
                            t("暂时无法添加");
                            return;
                        }
                        //types.addAll(belongTypePage);
                        types.clear();
                        for (BelongType belongType : belongTypePage) {
                            if (!"project_trend".equalsIgnoreCase(belongType.getCategoryCode())) {
                                types.add(belongType);
                            }
                        }
                        int position = 0;
                        ArrayList<String> strings = new ArrayList<>();
                        for (BelongType belongType : types) {
                            String categoryName = belongType.getCategoryName();
                            String belongTypeCategoryCode = belongType.getCategoryCode();
                            if (belongTypeCategoryCode.equals(categoryCode)) {
                                position = types.indexOf(belongType);
                            }
                            strings.add(categoryName);
                        }
                        String[] toArray = strings.toArray(new String[strings.size()]);
                        spinnerType.setAdapter(new SpinnerAdapter(getActivity(), toArray));


                        spinnerType.setSelection(position);
                    }

                    @Override
                    public void onFinal() {

                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposables(d);
                    }
                });

    }

    private void netProjectList() {
        ApiFactory.getInstance()
                .getSimples("2,4", "1", true)
                .compose(RxSchedulers.<Data<ArrayList<Project>>>io_main())
                .subscribe(new ComObserver<ArrayList<Project>>() {
                    @Override
                    public void onSuccess(ArrayList<Project> projectPage) {
                        if (projectPage == null) {
                            t("暂时无法添加");
                            return;
                        }
                        projects.clear();
                        projects.addAll(projectPage);

                        ArrayList<String> strings = new ArrayList<>();
                        for (Project project : projectPage) {
                            strings.add(project.getProjectName());
                        }
                        String[] toArray = strings.toArray(new String[strings.size()]);
                        spinnerProject.setAdapter(new SpinnerAdapter(getActivity(), toArray));
                    }

                    @Override
                    public void onFinal() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        t("网络异常，请返回重试");
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposables(d);
                    }
                });
    }


    @Override
    protected void initUiAndListener() {
        super.initUiAndListener();

        proWorkTrendId = getIntent().getLongExtra(PROWORKTRENDID, -1);
        categoryCode = getIntent().getStringExtra(CATEGORYCODE);
        reciveData = (HashMap<String, String>) getIntent().getSerializableExtra(DATA);


        if (proWorkTrendId == -1) {
            proWorkTrendId = null;
        }

        if (proWorkTrendId == null) {
            titleBar.setTitle("新增工作动态");
        } else {
            titleBar.setTitle("更新工作动态");
        }

        time = TimeUtil.getCurrentTimeTen();
        if (!TextUtils.isEmpty(reciveData.get("issueTime"))) {
            time = reciveData.get("issueTime");
        }
        timeTv.setText(time);

        String trendTitile = reciveData.get("trendTitile");
        if (trendTitile == null) {
            trendTitile = "";
        }
        titleEdit.setText(trendTitile);

        String trendHtmlContent = reciveData.get("trendHtmlContent");
        if (proWorkTrendId!=null) {
            getProjectWorkTrendHtmlContentInfo();
        } else{
            if (trendHtmlContent == null) {
                trendHtmlContent="";
            } else {
                trendContentEdit.setText(trendHtmlContent);
            }
        }

        titleBar.setOnClickListenerOfRight(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commit();
            }
        });
    }

    private void commit() {
        /*
        if (projects.isEmpty()) {
            return;
        }
        */
        if (types.isEmpty()) {
            return;
        }

        String titleName = getTitleName();
        String remark = getRemark();

        HashMap<String, String> param = new HashMap<>();

        /*
        int itemPosition = spinnerProject.getSelectedItemPosition();
        Project project = projects.get(itemPosition);
        param.put("projectId", String.valueOf(project.getProjectId()));
        */

        int itemPositionType = spinnerType.getSelectedItemPosition();
        BelongType belongType = types.get(itemPositionType);
        param.put("trendType", String.valueOf(belongType.getCategoryCode()));
        param.put("saveType", "submit");
        param.put("trendTitile", titleName);
        param.put("issueTime", time);

        String trendHtmlContent = trendContentEdit.getText().toString().trim();
        param.put("trendHtmlContent", trendHtmlContent);

        if (proWorkTrendId != null) {
            param.put("proWorkTrendId", String.valueOf(proWorkTrendId));
        }

        ArrayList<String> photoPaths = getPhotoPaths();

        if (!photoPaths.isEmpty()) {

            String[] fileRemark = new String[photoPaths.size()];
            for (int i = 0; i < photoPaths.size(); i++) {
                fileRemark[i] = remark;
            }
            param.put("uploadFileRemark", JsonUtils.toJson(fileRemark));

        }

        HashMap<String, RequestBody> bodyHashMap = FormUtil.AddHeader(param, "uploadFile", photoPaths);
        /*
        HashMap<String, RequestBody> bodyHashMap = FormUtil.AddHeader(param);

        for (File photoFile : photoFiles) {
            String key = "uploadFile\",filename=\"" + photoFile.getName();
            bodyHashMap.put(key, RequestBodyUtil.get(photoFile));
        }
        */

        final ProgressDialog dialog = ProgressDialog.show(this, "提示", "正在提交数据");

        ApiFactory.getInstance()
                .saveProjectWorkTrendInfo(bodyHashMap)
                .compose(RxSchedulers.<Data>io_main())
                .subscribe(new Consumer<Data>() {
                    @Override
                    public void accept(Data data) throws Exception {
                        setResult(600);
                        t("提交成功");
                        finish();
                        dialog.dismiss();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        t("提交失败");
                        dialog.dismiss();
                    }
                });
    }

    private String getRemark() {
        String remark = remarkEdit.getText().toString().trim();
        return remark;
    }

    private String getTitleName() {
        return titleEdit.getText().toString().trim();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_create_project_trend;
    }

    /**
     * @param activity
     * @param proWorkTrendId 不为-1就是修改,-1为新增
     */
    public static void start(Activity activity, Long proWorkTrendId, String categoryCode) {
        Intent intent = new Intent(activity, CreateProjectTrendActivity.class);
        intent.putExtra(PROWORKTRENDID, proWorkTrendId);
        intent.putExtra(CATEGORYCODE, categoryCode);
        activity.startActivityForResult(intent, 225);
    }

    public static void start(Activity activity, Long proWorkTrendId, String categoryCode, HashMap<String, String> hashMap) {
        Intent intent = new Intent(activity, CreateProjectTrendActivity.class);
        intent.putExtra(PROWORKTRENDID, proWorkTrendId);
        intent.putExtra(CATEGORYCODE, categoryCode);
        intent.putExtra(DATA, hashMap);
        activity.startActivityForResult(intent, 225);
    }


    @Override
    protected GridView getPhotoGv() {
        return gridView;
    }

    @OnClick(R.id.time_tv)
    public void onViewClicked() {
        final DatePickerDiaglog diaglog1 = new DatePickerDiaglog(getActivity());
        diaglog1.show();
        diaglog1.setCanceledOnTouchOutside(true);
        diaglog1.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                time = diaglog1.getTime();
                timeTv.setText(time);
            }
        });
    }
}